package com.example.voicedet;



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Timer;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.location.Location;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.example.mic.BigWindow;
import com.example.mic.FloatWindowBigView;
import com.example.preference.UserPreference;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUnderstander;
import com.iflytek.cloud.SpeechUnderstanderListener;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.UnderstanderResult;
import com.iflytek.cloud.VoiceWakeuper;
import com.iflytek.cloud.WakeuperListener;
import com.iflytek.cloud.WakeuperResult;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.cloud.util.ResourceUtil;
import com.iflytek.cloud.util.ResourceUtil.RESOURCE_TYPE;
//import com.ql.activity.Alarm;
//import com.ql.activity.AlarmReceiver;
import com.zl.api.RomControl;


public class WindowService extends Service {

	private ScreenFloatView mScreeFloatView;
	
	private WindowManager mWindowManager;
	private AudioManager audiomanager;
	private WindowManager.LayoutParams mWindowParams = new WindowManager.LayoutParams();
	private SessionLinearLayout mViewRoot;
	 
	private UserPreference mUserPreference;
	
	// 设置门限值 ： 门限值越低越容易被唤醒
	private final static int MAX = 60;
	private final static int MIN = -20;
	private int curThresh = 40;
	public  int xunfei_volum;
	
	
	//图灵机器人 科大讯飞开放语义***/
	protected static final int MSG_SUCCESS = 0;
	protected static final int MSG_FAILURE = 1;
	private String tulingResult;
	private Thread tulingThread;
	private Boolean isRun;
	
	private String ServiceType = "Null";
	
	/** 大悬浮窗view的实例 */
	public static FloatWindowBigView bigWindow;
	
	//高德定位实例
	private LocationManagerProxy aMapManager;
	public String Location_City = "";
	public String Location_District = "";
	public String Location_Type;
	public String Location_CityCode;
	double Location_Lng;
	double Location_Lat;
	
	//语音视频实例........................By Si Xiangjun
	private String video_keywords = "";
	private String video_actor = "";
	private String video_director = "";
	private String video_videoCategory = "";
	private String video_episode = "";
	
	
	
	Timer timer = new Timer();
	

/*WindowService初始化*/
	public void onCreate() {
		Log.d("WindowService", "onCreate");
		//初始化SharedPreference实例
		mUserPreference = new UserPreference(this);
		//初始化FloatView实例
		mScreeFloatView = new ScreenFloatView(this);
		mWindowManager  = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		audiomanager    = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		//注册SharedPreference监听
		registerListener();
		//网络状态监听器
		Net_registerReceiver();
		

		//从SharedPreference中读取相关参数，根据参数初始化WindowService对应的服务
		if(mUserPreference.getBoolean(UserPreference.KEY_ENABLE_FLOATSHOW, true))
		{
			showFloatView();
		}
		else
		{
			hideFloatView();
		}
		
		Init_SDK();
		SDK_setParam();

		mUserPreference.putBoolean(UserPreference.KEY_CANCEL_BUG, false);
		
		if(checkNetworkState())
		{
			mUserPreference.putString(UserPreference.Net_State, "Connected");
			if(mUserPreference.getBoolean(UserPreference.KEY_ENABLE_WAKEUP, true))
			{
				Init_SDK();
				SDK_setParam();
				WakeUp();
			}
			else
			{
				Xunfei_Stop();
			}
			XunFei_init_flag = true;
			offline_XunFei_init_flag = false;
		}
		else
		{
			mUserPreference.putString(UserPreference.Net_State, "NotConnected");
			mIat = SpeechRecognizer.createRecognizer(WindowService.this, mInitListener);
			// 初始化听写Dialog,如果只使用有UI听写功能,无需创建SpeechRecognizer
				
			// 初始化合成对象
			mTts = SpeechSynthesizer.createSynthesizer(WindowService.this, mTtsInitListener);
				
			offlineSharedPreferences = getSharedPreferences("com.iflytek.setting", Activity.MODE_PRIVATE);
			XunFei_init_flag = false;
			offline_XunFei_init_flag = true;
		}
		
	}
	
	
	
/*显示小悬浮窗口*/
	public void showFloatView() {
		if (!mScreeFloatView.isShown()) {
			mScreeFloatView.show();
		}
	}
/*关闭小悬浮窗口*/	
	public void hideFloatView() {
		if (mScreeFloatView.isShown()) {
			mScreeFloatView.hide();
		}
	}
	
	//网络状态监听器
	public class ConnectionChangeReceiver extends BroadcastReceiver {
	    @Override
	    public void onReceive(Context context, Intent intent) {
	        ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	        NetworkInfo  mobNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
	        NetworkInfo  wifiNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
	        
	        if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
	        	mUserPreference.putString(UserPreference.Net_State, "NotConnected");
	        	//改变背景或者 处理网络的全局变量
	        }else {
				mUserPreference.putString(UserPreference.Net_State, "Connected");
	            //改变背景或者 处理网络的全局变量
	        }
	    }
	}
	//网络状态监听 注册
	private  void Net_registerReceiver(){
        IntentFilter filter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        ConnectionChangeReceiver myReceiver=new ConnectionChangeReceiver();
        this.registerReceiver(myReceiver, filter);
    }
	
	private OnClickListener mOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View view) {
			if(checkNetworkState())
			{
				if (view == mScreeFloatView.getFloatMicInstance()) {
					Log.d("WindowService", "onClick");
					
					mTts.startSpeaking("你好主人，你有什么问题？", mTtsListener);
					sound_get();
					if(Location_City.length()>1)
					{}
					else
					{startAmap();}
				} else if (view.getId() == R.id.bottomCancelBtn) {
					Log.d("WindowService", "cancel button onClick");
	
				}
			}
			else
			{
				offline_tTs(offline_mTtsListener_1,"我是小为，你好，初次见面请多多关照");	// 开始合成
			}
		}
	};
	
	
	
	//离线 初始化监听器。/
	private InitListener mInitListener = new InitListener() {

		@Override
		public void onInit(int code) {
			Log.d(TAG, "SpeechRecognizer init() code = " + code);
			if (code != ErrorCode.SUCCESS) {
        	}
		}
	};
	
	//离线语音合成 初期化监听。
	private InitListener mTtsInitListener = new InitListener() {
		@Override
		public void onInit(int code) {
			Log.d(TAG, "InitListener init() code = " + code);
			if (code != ErrorCode.SUCCESS) {
        	}		
		}
	};
	
	
	//离线语音识别初始化
	private SharedPreferences offlineSharedPreferences;
	public void Offline_Iat_setParam(){
		// 清空参数
		mIat.setParameter(SpeechConstant.PARAMS, null);
		String lag = offlineSharedPreferences.getString("iat_language_preference", "mandarin");
		if (lag.equals("en_us")) {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
		}else {
			// 清空参数
			mTts.setParameter(SpeechConstant.PARAMS, null);
			//设置合成
			//设置发音人
			mTts.setParameter(SpeechConstant.VOICE_NAME,"vinn");
			//设置语速
			mTts.setParameter(SpeechConstant.SPEED,"50");
			//设置音调
			mTts.setParameter(SpeechConstant.PITCH,"50");
			//设置音量
			mTts.setParameter(SpeechConstant.VOLUME,"60");
			//设置播放器音频流类型
			mTts.setParameter(SpeechConstant.STREAM_TYPE,"3");
			
			/***语音听写设置***/
			// 清空参数
			mIat.setParameter(SpeechConstant.PARAMS, null);
			
			mIat.setParameter(SpeechConstant.DOMAIN, "iat");
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
			// 设置语言区域
			mIat.setParameter(SpeechConstant.ACCENT,"mandarin");
		}
		mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
	}
	
	/**
	 * 参数设置
	 * @param param
	 * @return 
	 */
	private void offline_tTs(SynthesizerListener mTtsListener,String xiaowei){	
		//设置合成
		mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
		//设置发音人 voicer为空默认通过语音+界面指定发音人。
		mTts.setParameter(SpeechConstant.VOICE_NAME,"");

		//设置播放器音频流类型
		mTts.setParameter(SpeechConstant.STREAM_TYPE,offlineSharedPreferences.getString("stream_preference", "1"));//0则为听筒
		int code = mTts.startSpeaking(xiaowei, mTtsListener);
		if (code != ErrorCode.SUCCESS) {			
		}
	}
	
	
	//离线 合成回调监听。
		//缓冲进度
		private int mPercentForBuffering = 0;	
		//播放进度
		private int mPercentForPlaying = 0;
	private SynthesizerListener offline_mTtsListener_1 = new SynthesizerListener() {

		public void onBufferProgress(int percent, int beginPos, int endPos,String info) 
		{	mPercentForBuffering = percent;	}

		public void onSpeakProgress(int percent, int beginPos, int endPos) 
		{	mPercentForPlaying = percent;	}

		public void onCompleted(SpeechError error) 
		{
			if(error == null)
			{	
				hideFloatView();
				BigWindow.createBigWindow(getApplicationContext(),0);//创建 大悬浮窗，监听音量检测UI
				
				Offline_Iat_setParam();
				mIat.startListening(offline_recognizerListener);
			}
			else if(error != null)
			{	}
		}

		@Override
		public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSpeakBegin() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSpeakPaused() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSpeakResumed() {
			// TODO Auto-generated method stub
			
		}


	};
	
	private SynthesizerListener offline_mTtsListener_2 = new SynthesizerListener() {

		public void onBufferProgress(int percent, int beginPos, int endPos,String info) 
		{	}

		public void onSpeakProgress(int percent, int beginPos, int endPos) 
		{	}

		public void onCompleted(SpeechError error) 
		{
			if(error == null)
			{	

			}
			else if(error != null)
			{	}
		}

		@Override
		public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSpeakBegin() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSpeakPaused() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSpeakResumed() {
			// TODO Auto-generated method stub
			
		}


	};
	
	/*** 听写UI监听器 */
	private RecognizerListener offline_recognizerListener = new RecognizerListener()
	{
		public void onResult(RecognizerResult results, boolean isLast) {
		Log.d("Result:",results.getResultString ());
		
		String text = JsonParser.parseIatResult(results.getResultString());
		if(mUserPreference.getBoolean(UserPreference.KEY_ENABLE_FLOATSHOW, true))
		{
			showFloatView();
		}
		BigWindow.removeBigWindow(getApplicationContext());//移除 大悬浮窗，关闭监听音量检测UI
		
		offline_tTs(offline_mTtsListener_2,text);	// 开始合成
		}
		//会话发生错误回调接口
		public void onError(SpeechError error) {
		error.getPlainDescription(true); //获取错误码描述
		}
		//开始录音
		public void onBeginOfSpeech() {}
		//音量值0~30
		public void onVolumeChanged(int volume){BigWindow.updateBigWindow(volume/3);Log.d("xunfei_vol" , "识别音量"+(volume/3));}
		//结束录音
		public void onEndOfSpeech() {}
		//扩展用接口
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {}
	
		};

	
	private boolean XunFei_init_flag = false;
	private boolean offline_XunFei_init_flag = false;
	
	
/*注册监听器*/	
	private void registerListener() {
		mScreeFloatView.setOnClickListener(mOnClickListener);
		mUserPreference.registerOnSharedPreferenceChangeListener(mPreferenceChangeListener);
	}
/*释放监听器*/		
	private void unregisterListener() {
		mScreeFloatView.setOnClickListener(null);
		mUserPreference.unregisterOnSharedPreferenceChangeListener(mPreferenceChangeListener);
	}
	
/*属性改变监听回调*/		
	public OnSharedPreferenceChangeListener mPreferenceChangeListener = new OnSharedPreferenceChangeListener() {

		@Override
		public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
			Log.d("PreferenceChange", "onSharedPreferenceChanged: key " + key);
			if(key.equals(UserPreference.Net_State))
			{
				if(mUserPreference.getString(UserPreference.Net_State, "Null").equals("Connected"))
				{
					Log.d("Net_State","网络已连接");
					
					if(mUserPreference.getBoolean(UserPreference.KEY_ENABLE_WAKEUP, true))
					{
						offline_Xunfei_Stop();
						Init_SDK();
						SDK_setParam();
						WakeUp();
					}
					else
					{
						offline_Xunfei_Stop();
						Init_SDK();
						SDK_setParam();
					}
					XunFei_init_flag = true;
					offline_XunFei_init_flag = false;
				}
				else if(mUserPreference.getString(UserPreference.Net_State, "Null").equals("NotConnected"))
				{
					Log.d("Net_State","网络连接失败");
					Xunfei_Stop();
					// 初始化识别对象
					mIat = SpeechRecognizer.createRecognizer(WindowService.this, mInitListener);
					// 初始化听写Dialog,如果只使用有UI听写功能,无需创建SpeechRecognizer
						
					// 初始化合成对象
					mTts = SpeechSynthesizer.createSynthesizer(WindowService.this, mTtsInitListener);
						
					offlineSharedPreferences = getSharedPreferences("com.iflytek.setting", Activity.MODE_PRIVATE);
					
					XunFei_init_flag = false;
					offline_XunFei_init_flag = true;
				}
					
			}
			
			if(key.equals(UserPreference.KEY_ENABLE_WAKEUP))
			{
				if(mUserPreference.getString(UserPreference.Net_State, "Null").equals("Connected"))
				{
					if(mUserPreference.getBoolean(UserPreference.KEY_ENABLE_WAKEUP, true))
					{
						offline_Xunfei_Stop();
						Init_SDK();
						SDK_setParam();
						WakeUp();
					}
					else
					{
						Xunfei_Stop();
					}
					XunFei_init_flag = true;
					offline_XunFei_init_flag = false;
				}
				else if(mUserPreference.getString(UserPreference.Net_State, "Null").equals("NotConnected"))
				{
					Log.d("Net_State","网络连接失败");
					Xunfei_Stop();
					// 初始化识别对象
					mIat = SpeechRecognizer.createRecognizer(WindowService.this, mInitListener);
					// 初始化听写Dialog,如果只使用有UI听写功能,无需创建SpeechRecognizer
						
					// 初始化合成对象
					mTts = SpeechSynthesizer.createSynthesizer(WindowService.this, mTtsInitListener);
						
					offlineSharedPreferences = getSharedPreferences("com.iflytek.setting", Activity.MODE_PRIVATE);
					
					XunFei_init_flag = false;
					offline_XunFei_init_flag = true;
				}
			}
			
			if(key.equals(UserPreference.KEY_ENABLE_FLOATSHOW))
			{
				if(mUserPreference.getBoolean(UserPreference.KEY_ENABLE_FLOATSHOW, true))
				{
					showFloatView();
				}
				else
				{
					hideFloatView();
				}
			}
			
			
			if(key.equals(UserPreference.KEY_CANCEL_BUG))
			{
				if(mUserPreference.getBoolean(UserPreference.KEY_CANCEL_BUG, true))
				{
					if(mUserPreference.getString(UserPreference.Net_State, "Null").equals("NotConnected"))
					{
						mIat = SpeechRecognizer.createRecognizer(WindowService.this, mInitListener);
						// 初始化听写Dialog,如果只使用有UI听写功能,无需创建SpeechRecognizer
							
						// 初始化合成对象
						mTts = SpeechSynthesizer.createSynthesizer(WindowService.this, mTtsInitListener);
							
						offlineSharedPreferences = getSharedPreferences("com.iflytek.setting", Activity.MODE_PRIVATE);
					}
					else if(mUserPreference.getBoolean(UserPreference.KEY_ENABLE_WAKEUP, true))
					{
						Xunfei_Stop();
						Init_SDK();
						SDK_setParam();
						WakeUp();
					}
					else
					{
						Xunfei_Stop();
					}
					
					if(mUserPreference.getBoolean(UserPreference.KEY_ENABLE_FLOATSHOW, true))
					{
						showFloatView();
					}
					else
					{
						hideFloatView();
					}
					mUserPreference.putBoolean(UserPreference.KEY_CANCEL_BUG, false);
					sound_release();
				}
				else
				{}
			}
			
			
		}
	};
	
	
	
/***语音唤醒变量***/   // 语音唤醒对象
	private VoiceWakeuper mIvw;
/***语音合成变量***/   // 语音合成对象
	private SpeechSynthesizer mTts;
// 默认云端发音人
	public static String voicerCloud="vinn";
/***语音听写变量***/  // 语音听写对象
	private SpeechRecognizer mIat;
/***语义理解变量***/  // 语义理解对象（语音到语义）。
	private SpeechUnderstander mSpeechUnderstander;
	
	
/***讯飞语音初始化***/
	public void Init_SDK() {
    	/***证书***/
    	SpeechUtility.createUtility(this, SpeechConstant.APPID +"=55ba0168");
    	
    	/***语音唤醒初始化***/
        // 加载识唤醒地资源，resPath为本地识别资源路径
 		StringBuffer param = new StringBuffer();
 		String resPath = ResourceUtil.generateResourcePath(this,RESOURCE_TYPE.assets, "ivw/" + "55ba0168" + ".jet");
 		param.append(ResourceUtil.IVW_RES_PATH + "=" + resPath);
 		param.append("," + ResourceUtil.ENGINE_START + "=" + SpeechConstant.ENG_IVW);
 		boolean ret = SpeechUtility.getUtility().setParameter(
 				ResourceUtil.ENGINE_START, param.toString());
 		if (!ret) {
 			Log.d("xunfei", "启动本地引擎失败！");
 		}
 		
 		/***语音唤醒初始化***/
 		// 初始化唤醒对象
 	 	mIvw = VoiceWakeuper.createWakeuper(this, null);
 	 	
 		/***语音合成初始化***/
 	 	// 初始化合成对象
 		mTts = SpeechSynthesizer.createSynthesizer(this, null);
 		
 		/***语音听写初始化***/
 		// 初始化识别对象
 		mIat = SpeechRecognizer.createRecognizer(this, null);
 		
 		/***语义理解初始化***/
 		// 初始化对象
 		mSpeechUnderstander = SpeechUnderstander.createUnderstander(this, null);
    }
	
	
/*** 语音参数设置。 */
	public void SDK_setParam(){
    	/***语音合成设置***/
		// 清空参数
		mTts.setParameter(SpeechConstant.PARAMS, null);
		//设置合成
		//设置使用云端引擎
		mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
		//设置发音人
		mTts.setParameter(SpeechConstant.VOICE_NAME,voicerCloud);
		//设置语速
		mTts.setParameter(SpeechConstant.SPEED,"50");
		//设置音调
		mTts.setParameter(SpeechConstant.PITCH,"50");
		//设置音量
		mTts.setParameter(SpeechConstant.VOLUME,"80");
		//设置播放器音频流类型
		mTts.setParameter(SpeechConstant.STREAM_TYPE,"3");
		
		/***语音听写设置***/
		// 清空参数
		mIat.setParameter(SpeechConstant.PARAMS, null);
		
		mIat.setParameter(SpeechConstant.DOMAIN, "iat");
		// 设置语言
		mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
		// 设置语言区域
		mIat.setParameter(SpeechConstant.ACCENT,"mandarin");
		
		/***语义理解设置***/
		// 设置语言
		mSpeechUnderstander.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
		// 设置语言区域
		mSpeechUnderstander.setParameter(SpeechConstant.ACCENT,"mandarin");
		// 设置语音前端点
		mSpeechUnderstander.setParameter(SpeechConstant.VAD_BOS, "4000");
		// 设置语音后端点
		mSpeechUnderstander.setParameter(SpeechConstant.VAD_EOS, "1000");
		// 设置标点符号
		mSpeechUnderstander.setParameter(SpeechConstant.ASR_PTT, "1");
    }
	
	
/*** 语音唤醒开始监听。 */
	public void WakeUp() {
     	//非空判断，防止因空指针使程序崩溃
		ServiceType = "Null";
 		mIvw = VoiceWakeuper.getWakeuper();
 		if(mIvw != null) {
 			// 清空参数
 			mIvw.setParameter(SpeechConstant.PARAMS, null);
 			// 唤醒门限值，根据资源携带的唤醒词个数按照“id:门限;id:门限”的格式传入
 			mIvw.setParameter(SpeechConstant.IVW_THRESHOLD, "0:" + curThresh);
 			// 设置唤醒模式
 			mIvw.setParameter(SpeechConstant.IVW_SST, "wakeup");
 			// 设置持续进行唤醒
 			mIvw.setParameter(SpeechConstant.KEEP_ALIVE, "1");
 			mIvw.startListening(mWakeuperListener);
 			Log.d("xunfei", "唤醒初始化成功");
 		} else {
 			Log.d("xunfei", "唤醒未初始化");
 		}
     }
	
/*** 语音唤醒停止监听 */
	public void Sleep() {
    	mIvw = VoiceWakeuper.getWakeuper();
		if (mIvw != null) {
			mIvw.destroy();
		} else {
			Log.d("xunfei", "唤醒未初始化");
		}
    }
	

	
	
/*** 唤醒回调监听。 */
	public WakeuperListener mWakeuperListener = new WakeuperListener() {
		public void onResult(WakeuperResult result) {
			try {
				String text = result.getResultString();
				JSONObject object;
				object = new JSONObject(text);
				if(object.optString("sst").equals("wakeup")) {
					Log.d("xunfei", "wake up successfully!");
					
//					ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);  
//					ComponentName cn = am.getRunningTasks(1).get(0).topActivity;  
//					am.getRunningAppProcesses();
//					Log.d(TAG, "pkg:"+cn.getPackageName());  
//					Log.d(TAG, "cls:"+cn.getClassName());
					
					//2 语音合成进行应答
					int code = mTts.startSpeaking("你好主人，你有什么问题？", mTtsListener);
					sound_get();
					if(Location_City.length()>1)
						{}
					else
						{startAmap();}
					if (code != ErrorCode.SUCCESS) {Log.d("xunfei", "语音合成失败,错误码: " + code);}
				} else {
					Log.d("xunfei", "wake up error!");
				}
			} catch (JSONException e) {e.printStackTrace();}

		}

		public void onError(SpeechError error) {}

		public void onBeginOfSpeech() {}

		public void onEvent(int eventType, int isLast, int arg2, Bundle obj) {}
	};
	
/*** 听写UI监听器 */
	public RecognizerDialogListener recognizerDialogListener=new RecognizerDialogListener(){
		public void onResult(RecognizerResult result, boolean isLast) {
			Log.d("xunfei", "recognizer result：" + result.getResultString());
		}
		/*** 识别回调错误.*/
		public void onError(SpeechError error) {
			//showTip(error.getPlainDescription(true));
		}
	};
	
/*** 合成回调监听。 */
	public SynthesizerListener mTtsListener = new SynthesizerListener() {
		public void onSpeakBegin() {}

		public void onSpeakPaused() {}

		public void onSpeakResumed() {}

		public void onBufferProgress(int percent, int beginPos, int endPos,	String info) {}

		public void onSpeakProgress(int percent, int beginPos, int endPos) {}

		public void onCompleted(SpeechError error) {
			if(error == null)
			{//3 监听用户口令
				/***语音唤醒停止监听***/
				Sleep();
				Log.d("xunfei", "sleep");
				
				hideFloatView();
				BigWindow.createBigWindow(getApplicationContext(),0);//创建 大悬浮窗，监听音量检测UI
				
				if(mSpeechUnderstander.isUnderstanding())// 开始前检查状态
					{mSpeechUnderstander.stopUnderstanding();}
				else {
					int ret = mSpeechUnderstander.startUnderstanding(mRecognizerListener);
					if(ret != 0){Log.d("xunfei", "语义理解失败,错误码:"	+ ret);}
					else {Log.d("xunfei", "语义理解开始");}
				}
			}
			else if(error != null)
			{Log.d("xunfei", error.getPlainDescription(true));}
		}

		public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {}
	};
	
	
	/*** 语义理解回调。    */
	public SpeechUnderstanderListener mRecognizerListener = new SpeechUnderstanderListener() {

		@Override
		public void onResult(final UnderstanderResult result) {
			//Android4.0以上不能在主线程中访问网络，新开线程
	       	Runnable tulingRunnable = new Runnable() 
	       	{
	    		public void run() {
	    			if(isRun) {
	    				Message msg = new Message();
	    				String text = new String();
	    				if(null != result) {
	    					text = result.getResultString();
							if (!TextUtils.isEmpty(text)) {//获取图灵机器人应答成功
			    				msg.what = MSG_SUCCESS;
			    				msg.obj = text;
			    				tulingHandler.sendMessage(msg);
							}
	    				} else {//获取图灵机器人应答失败，网络错误
	    					msg.what = MSG_FAILURE;
	    					tulingHandler.sendMessage(msg);
	    				}
	    			}
	    		}
	    	};
	       	
	       	if(tulingThread == null) {
				isRun = true;
				tulingThread = new Thread(tulingRunnable);  
				tulingThread.start();//线程启动  
            }
            else {
                Log.d("xunfei" , "线程已启动！");  
            }
	       	/** 此处添加语音唤醒监听逻辑上不大对，因为上面新开线程处理网络内容时，按道理不应该开始监听用户唤醒。
	       	 * 但实时证明这并补冲突，上面网络处理然后读出处理结果的过程中，对其进行唤醒并不成功      	 */
			//4 语音唤醒开始监听
			WakeUp();
			
			if(mUserPreference.getBoolean(UserPreference.KEY_ENABLE_FLOATSHOW, true))
			{
				showFloatView();
			}
			BigWindow.removeBigWindow(getApplicationContext());//移除 大悬浮窗，关闭监听音量检测UI
		}

        public void onVolumeChanged(int v) {BigWindow.updateBigWindow(v/3);;Log.d("xunfei_vol" , "识别音量"+(v/3)); }

        public void onEndOfSpeech() {}

        public void onBeginOfSpeech() {}

		public void onError(SpeechError error) {
			Log.d("xunfei", "onError Code："	+ error.getErrorCode());
			//10114错误：查看网络环境是否正常，查看是否使用的是公司网络（很多公司网络会将一些网络地址和端口屏蔽掉），查看讯飞的服务器地址和端口是不是被屏蔽（服务器地址dev.voicecloud.cn 端口号是1028和80）。
			Log.d("xunfei", "语义无法识别");
		//语音合成进行回答
			String text = "我还不会那么多，您再慢慢讲一遍试试";
			int code = mTts.startSpeaking(text, mTtsListener2);
			if (code != ErrorCode.SUCCESS) {
				Log.d("xunfei", "语音合成失败,错误码: " + code);
			}
			
			if(mUserPreference.getBoolean(UserPreference.KEY_ENABLE_FLOATSHOW, true))
			{
				showFloatView();
			}
			BigWindow.removeBigWindow(getApplicationContext());//移除 大悬浮窗，关闭监听音量检测UI
		}

		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {}
    };

/***根据语义理解的状态返回值，启动线程  */
    private Handler tulingHandler = new Handler() {
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what) {
			case MSG_SUCCESS:
				tulingResult = (String) msg.obj;
				Log.d("xunfei", "tulingResult:" + tulingResult);
				isRun = false;
				tulingThread.interrupt();
				tulingThread = null;
				tulingPraser(tulingResult);
				break;
			case MSG_FAILURE:
				Log.d("xunfei", "网络错误，本地wifi或者远程服务器异常");
				break;
			}
		}
		
	};
	
/*** 合成回调监听2。 */
	private SynthesizerListener mTtsListener2 = new SynthesizerListener() {
		public void onBufferProgress(int arg0, int arg1, int arg2, String arg3) {}

		public void onCompleted(SpeechError arg0) 
		{//4 语音唤醒开始监听
			//stopAmap();
			WakeUp();
			sound_release();
		}

		public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {}

		public void onSpeakBegin() {}

		public void onSpeakPaused() {}

		public void onSpeakProgress(int arg0, int arg1, int arg2) {}

		public void onSpeakResumed() {}
		
	};
	
	public static String TAG = "tulingPraser";
/***语义解析 且执行相应的操作*/
	public void tulingPraser(String jsonResult) {
		try {
			JSONObject object;
			object = new JSONObject(jsonResult);

			String service;
			String operation;
			
			if(object.optString("text").contains("1234"))
			{
				String text = "丁丁是无锡吾芯互联科技一位有才的程序员兼单身小贵族";
				int code = mTts.startSpeaking(text, mTtsListener2);
				if (code != ErrorCode.SUCCESS) {
					Log.d(TAG, "语音合成失败,错误码: " + code);}
				WakeUp();
			}
			else if(object.optString("service") != null)
			{
				service   = object.optString("service");     //获取识别的      服务类别}
				operation = object.optString("operation");   //获取识别的     操作码

				String text = "";
				int    code = 0;
				Log.d(TAG, "听到的信息为："+service);
				Log.d(TAG,object.optString("text"));
				
				String ask_text  = object.optString("text");	
			
				if(object.optString("text").equals("拍照。")||object.optString("text").equals("拍照片。")) {
					Log.d(TAG, "camera");
					PackageManager pm = getPackageManager();
					String packageManager ="com.example.camera";//这个包横屏有点问题
					Intent intent = pm.getLaunchIntentForPackage(packageManager);
					intent.putExtra("action", "camera");
					if(intent!=null){//MainActivity.this.startActivity(intent);
					}
					WakeUp();
			} 
			else if(object.optString("text").equals("录像。")||object.optString("text").equals("摄像。")) 
			{
				Log.d(TAG, "record");
				PackageManager pm = getPackageManager();
				String packageManager ="com.example.camera";
				Intent intent = pm.getLaunchIntentForPackage(packageManager);
				intent.putExtra("action", "record");
				if(intent!=null){
					//MainActivity.this.startActivity(intent);
				}
				WakeUp();
			} 
			else if(object.optString("text").equals("向前走。")||object.optString("text").equals("向前。")) 
			{
				Log.d(TAG, "go forword");
				//forward();
				WakeUp();
			} 
			else if(object.optString("text").equals("向后走。")||object.optString("text").equals("向后。")) 
			{
				Log.d(TAG, "back");
				//back();
				WakeUp();
			} 
			else if(object.optString("text").equals("向左转。")||object.optString("text").equals("向左走。")||object.optString("text").equals("向左。")) 
			{
				Log.d(TAG, "left");
				//left();
				WakeUp();
			} 
			else if(object.optString("text").equals("向右转。")||object.optString("text").equals("向右走。")||object.optString("text").equals("向右。")) 
			{
				Log.d(TAG, "right");
				//right();
				WakeUp();
			} 
			else if(object.optString("text").equals("停下。")||object.optString("text").equals("停止。")||object.optString("text").equals("停。")) 
			{
				Log.d(TAG, "stop");
				//stop();
				WakeUp();
			} 
				
				if(object.optString("text").equals("关闭按钮。") ||
						object.optString("text").equals("关闭悬浮窗口。") )
				{
					mUserPreference.putBoolean(UserPreference.KEY_ENABLE_FLOATSHOW, false);
				}
				else if(    object.optString("text").equals("讲笑话。") ||
							object.optString("text").equals("讲个笑话。") ||
							object.optString("text").equals("笑话。") ||
							object.optString("text").equals("说笑话。") )
				{
					//String joke_text = com.zl.api.joke.request("http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text","page=1");
					//Log.d(TAG,"笑话："+joke_text);
					
					WakeUp();
				}
				
				else if(service.equals("app")) //4.1---应用
				{
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots    = semantic.optJSONObject("slots");
					String name        = slots.optString("name");
					
					String[] package_name = new String[1];
					String[] class_name   = new String[1];
					if(operation.equals("LAUNCH"))//打开应用
					{	Log.d(TAG, "打开应用");
						
						if(name != null)   
						{
							com.zl.open_app.app_list.getAllApps(this,name,package_name,class_name);
							Log.d(TAG, "package_name = " + package_name[0] + "     class_name =" + class_name[0]);
							
							if(package_name[0] != "" && package_name[0] != null && class_name[0] != "" && class_name[0] != null)
							{
								RomControl.enterControl(this,RomControl.ROM_APP_LAUNCH, package_name[0], class_name[0]);
								text = "已经为您打开"+name;
							}
							else
							{
								text = "您还没有安装"+name;
							}
						}
						else
						{
							text = "您还没有安装应用程序"+name;
						}
						//语音合成进行回答
						
						code = mTts.startSpeaking(text, mTtsListener2);
						if (code != ErrorCode.SUCCESS) {
							Log.d(TAG, "语音合成失败,错误码: " + code);}
					}
					else if(operation.equals("UNINSTALL"))//卸载应用
					{
						
						//语音合成进行回答
						text = "暂不支持卸载程序";
						code = mTts.startSpeaking(text, mTtsListener2);
						if (code != ErrorCode.SUCCESS) {
							Log.d(TAG, "语音合成失败,错误码: " + code);}
					}
					else if(operation.equals("DOWNLOAD"))//下载应用
					{
						String category    = slots.optString("category");
						
						//语音合成进行回答
						text = "暂不支持程序下载";
						code = mTts.startSpeaking(text, mTtsListener2);
						if (code != ErrorCode.SUCCESS) {
							Log.d(TAG, "语音合成失败,错误码: " + code);}
					}
					else if(operation.equals("INSTALL"))//安装应用
					{
						
						//语音合成进行回答
						text = "暂不支持额外的应用安装";
						code = mTts.startSpeaking(text, mTtsListener2);
						if (code != ErrorCode.SUCCESS) {
							Log.d(TAG, "语音合成失败,错误码: " + code);}
					}
					else if(operation.equals("QUERY"))  //搜索应用
					{
						String category    = slots.optString("category");
						
						//语音合成进行回答
						text = "暂不支持程序搜索";
						code = mTts.startSpeaking(text, mTtsListener2);
						if (code != ErrorCode.SUCCESS) {
							Log.d(TAG, "语音合成失败,错误码: " + code);}
					}
					else if(operation.equals("EXIT"))  //退出或关闭应用
					{
						
						com.zl.open_app.app_list.getAllApps(this,name,package_name,class_name);
						Log.d(TAG, "package_name = " + package_name[0] + "     class_name =" + class_name[0]);

						RomControl.enterControl(this,RomControl.ROM_APP_EXIT, package_name[0], class_name[0]);
						
						//语音合成进行回答
						text = "已经为您关闭了"+name;
						code = mTts.startSpeaking(text, mTtsListener2);
						if (code != ErrorCode.SUCCESS) {
							Log.d(TAG, "语音合成失败,错误码: " + code);}
					}
				}
				else if(service.equals("baike"))  //4.2---百科
				{//Log.d(TAG, "打开应用");
					
					
					JSONObject answer   = object.optJSONObject("answer");
					String answer_text = answer.optString("text");	
					//text = "百科大全还在完善中，稍后就可以问我了";
					
					if(operation.equals("ANSWER"))
					{
						text = answer.optString("text");
						code = mTts.startSpeaking(text, mTtsListener2);
						if (code != ErrorCode.SUCCESS) {
							Log.d(TAG, "语音合成失败,错误码: " + code);}
					}
				}
				else if(service.equals("calc"))  //4.3---计算器
				{
					JSONObject answer   = object.optJSONObject("answer");
					String answer_text = answer.optString("text");
					//语音合成进行回答
					text = answer_text;
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("cookbook"))  //4.4---菜谱
				{
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots    = semantic.optJSONObject("slots");
					String dishName     = slots.optString("dishName");
					JSONObject webPage     = object.optJSONObject("webPage");
					String url          = webPage.optString("url");
					/////////-----------wheel while     需要添加菜谱的跳出  url
					RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
					//语音合成进行回答
					StringBuilder answer_1 = new StringBuilder("找到您要的");
					answer_1 = answer_1.append(dishName);
					answer_1 = answer_1.append("的做法了");
					text = answer_1.toString();
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("datetime")) //4.5----日期
				{
					JSONObject answer   = object.optJSONObject("answer");
					String answer_text  = answer.optString("text");
					
					//语音合成进行回答
					text = answer.optString("text");
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("faq"))      //4.6----社区问答
				{
					JSONObject answer   = object.optJSONObject("answer");
					String answer_text  = answer.optString("text");
					//语音合成进行回答
					text = answer.optString("text");
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("flight"))   //4.7----航班
				{
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots    = semantic.optJSONObject("slots");
					JSONObject startLoc = slots.optJSONObject("startLoc");
					JSONObject endLoc   = slots.optJSONObject("endLoc");
					JSONObject startDate;
					String     date  ;
					if(slots.optJSONObject("startDate")!=null)
					{
						startDate= slots.optJSONObject("startDate");
						date     = startDate.optString("date");
					}
					else
					{
						date     ="";
					}
					
					String start_c_addr = startLoc.optString("cityAddr");
					String start_pos    = startLoc.optString("poi");
					String end_c_addr   = endLoc.optString("cityAddr");
					String end_pos      = endLoc.optString("poi");
					
					String url = "http://touch.qunar.com/h5/flight/flightlist?";

					if(start_c_addr.equals(""))
					{
						if(Location_City.length()>=1)
						{
							Location_City =  Location_City.substring(0,Location_City.length()-1); 
							Log.d("Location_City","Location_City"+Location_City);
							url = url+"startCity="+Location_City+"&";
							url = url+"destCity="+end_c_addr+"&";
					
					
							url = url+"startDate="+date+"&";
							url = url+"backData=&";
							url = url+"flightType=oneWay";

							RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
							text = "已经找到以下的航班。请根据需求选择航线，订票请点击！";
						}
						else
						{
							text = "定位失败，请告诉我出发和到达城市的名称！";
						}
					}
					else
					{
						url = url+"startCity="+start_c_addr+"&";
						url = url+"destCity="+end_c_addr+"&";
					
					
						url = url+"startDate="+date+"&";
						url = url+"backData=&";
						url = url+"flightType=oneWay";

						RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
						text = "已经找到以下的航班。请根据需求选择航线，订票请点击！";
					}
					
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("hotel"))    //4.8----酒店
				{
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots    = semantic.optJSONObject("slots");
					JSONObject location = slots.optJSONObject("location");
					JSONObject checkinDate = slots.optJSONObject("checkinDate");
					String name         = slots.optString("name");
					String date         = checkinDate.optString("date");
					String c_addr       = location.optString("cityAddr");
					String pos          = location.optString("poi");
					String areaAddr          = location.optString("areaAddr");
					//语音合成进行回答
					
					String url = "http://touch.qunar.com/h5/hotel/hotellist?";
					
					
					if(c_addr.equals(""))
					{
						if(Location_City.length()>=1)
						{
							Location_City =  Location_City.substring(0,Location_City.length()-1); 
							if(Location_District.length()>=1)
							{Location_District =  Location_District.substring(0,Location_District.length()-1); }
						
							url = url + "city=" + Location_City + "&";
							url = url + "checkInDate=" + date + "&";
							url = url + "checkOutDate=&location=&";
							url = url + "keywords=" + Location_District + "&";
							url = url +"&pr=&level=&back=";
							RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
							text = "为您找到了附近的一些酒店";
						}
						else
						{
							text = "定位失败，请告诉我您要查找酒店的城市和区域";
						}
					}
					else
					{
						url = url + "city=" + c_addr + "&";
						url = url + "checkInDate=" + date + "&";
						url = url + "checkOutDate=&location=&";
						if(pos.length()>1)				{url = url + "keywords=" + pos + "&";}
						else if(areaAddr.length()>1) 	{url = url + "keywords=" + areaAddr + "&";}
						url = url +"&pr=&level=&back=";
						RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
						text = "已经为您找到相关的酒店";
					}
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("map"))     //4.9----地图
				{
					if(operation.equals("POSITION"))
					{
						JSONObject semantic = object.optJSONObject("semantic");
						JSONObject slots    = semantic.optJSONObject("slots");
						JSONObject location = slots.optJSONObject("location");
						String city = location.optString("city");
						String pos  = location.optString("poi");
						
					}
					else if(operation.equals("ROUTE"))
					{
						JSONObject semantic = object.optJSONObject("semantic");
						JSONObject slots    = semantic.optJSONObject("slots");
						JSONObject startLoc = slots.optJSONObject("startLoc");
						JSONObject endLoc   = slots.optJSONObject("endLoc");
						String start_city   = startLoc.optString("city");
						String start_addr   = startLoc.optString("cityAddr");
						String end_city     = endLoc.optString("city");
						String end_addr     = endLoc.optString("cityAddr");
					}
					//语音合成进行回答
					if(Location_City.length()>=1)
					{
						text = "您现在所处的位置是"+Location_Desc;
					}
					else
					{
						text = "定位失败，请重试";
					}
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("music"))    //4.10---音乐
				{
					ServiceType = "Music";
					JSONObject webPage  = object.optJSONObject("webPage");
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots;
					
					//mUserPreference.putString(UserPreference.Music_State, "Finish");
					Intent intent = new Intent();  
	                intent.setAction("com.allthings.music");  
	                intent.putExtra("CMD", "Finish");
	                sendBroadcast(intent); 
	                
					if(semantic.optJSONObject("slots")!=null)
					{
						slots    = semantic.optJSONObject("slots");
	
						String artist="";
						String song="";
						if(slots.optString("artist").length()>=1)
						{artist = slots.optString("artist");}
						else
						{artist = "";}
						if(slots.optString("song").length()>=1)
						{song = slots.optString("song");}
						else
						{song = "";}
						
						JSON_url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=qianqian&version=2.1.0";
						JSON_url = JSON_url + "&method=baidu.ting.search.common&format=json&query=";
						JSON_url = JSON_url + artist + song + "&page_no=1&page_size=300";
						Log.d("JSON_url_music",JSON_url);
						httpClientThread = new Thread(httpClientRunnable);
						httpClientThread.start();
						//语音合成进行回答
						//text = "酷我音乐修改中";
						code = mTts.startSpeaking(text, mTtsListener2);
						if (code != ErrorCode.SUCCESS) {
							Log.d(TAG, "语音合成失败,错误码: " + code);}
					}
					else
					{
						text = "音乐播放没有返回关键信息";
						code = mTts.startSpeaking(text, mTtsListener2);
						if (code != ErrorCode.SUCCESS) {
							Log.d(TAG, "语音合成失败,错误码: " + code);}
					}
				}
	//////////////////////////////////////////////////////////////////////////////////////////////////////////
	///////   从这里网上的代码中没有做完备的                       /////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////
				else if(service.equals("radio"))    //4.11---电台查询
				{
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots;
					String name       = null;
					String radio_code = null;
					String waveband   = null;
					String zone       = null;
					String category   = null;
					
					if(semantic.optJSONObject("slots") != null)
					{
						slots = semantic.optJSONObject("slots");
						if(slots.optString("name") != null)
						{name = slots.optString("name");}
						if(slots.optString("code") != null)
						{radio_code = slots.optString("code");}
						if(slots.optString("waveband") != null)
						{waveband = slots.optString("waveband");}
						if(slots.optString("zone") != null)
						{zone = slots.optString("zone");}
					}
									
					//语音合成进行回答
					text = "程序员同志，你还没有添加启动收音机的操作";
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("restaurant")) //4.12----餐馆
				{
					if(Location_City.length()>=1)
					{
						String url = "http://m.amap.com/search?query=";
						url = url + "美食";
						url = url + "&city=" + Location_CityCode + "&query_type=SPQ&";
						url = url + "geoobj=" + (Location_Lng-0.01) + "%7C" + (Location_Lat-0.008);
						url = url + "%7C" + (Location_Lng+0.01) + "%7C" + (Location_Lat+0.008);
						RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
						//语音合成进行回答
						text = "为您找到以下有关餐馆的结果";
					}
					else
					{
						text = "定位失败，未能为您找到附近的美食";
					}
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("schedule"))   //4.13----提醒 by Si Xiangjun
				{
//					Intent intent = new Intent();  
//	                intent.setAction("com.cn.daming.deskclock");  
//	                intent.putExtra("CMD", "Finish");
//	                sendBroadcast(intent); 
					
					
					//Calendar calendar ;
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots    = semantic.optJSONObject("slots");
					String name = slots.optString("name");
					JSONObject datetime = slots.optJSONObject("datetime");
					//String repeat;
					String content;
					//JSONObject location;
					
					String date,dateOrig,time,timeOrig,day,hour,minute;
					
					int flag = 1;//判断是语音提醒还是手动提醒的标志位
					int d=0;
					int h=0;
					int m=0;
					dateOrig = datetime.optString("dateOrig");
					time = datetime.optString("time");
					Log.d("reminder",time);
					timeOrig = datetime.optString("timeOrig");
					content = slots.optString("content");
					//获取一个月中的第几天
					date  = datetime.optString("date");
					day = date.substring(8);
					Log.d("reminder",day);
					try {
						d = Integer.parseInt(day);
						Log.d("reminder","day="+d);
					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
					//获取小时和分钟 
					hour = time.substring(0,2);
					Log.d("reminder",hour);
					try {
						h = Integer.parseInt(hour);
						Log.d("reminder","hour="+h);
					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
					minute = time.substring(3, 5);
					Log.d("reminder",minute);
					try {
						m = Integer.parseInt(minute);
						Log.d("reminder","minute="+m);
					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
					Intent intent = new Intent();  
	                intent.setAction("com.cn.daming.deskclock");  
	                intent.putExtra("CMD", "Finish");
	                intent.putExtra("flag_v", flag);
	                intent.putExtra("hour_v", h);
	                intent.putExtra("minute_v", m);
	                intent.putExtra("content_v", content);
	                sendBroadcast(intent); 
	                
					onTimeSet(flag,d,h,m,content);
					
					
//					if(operation.equals("CREATE"))
//					{
//						if(slots.optString("repeat") != null)
//						{repeat = slots.optString("repeat");}
//						if(slots.optString("content") != null)
//						{content = slots.optString("content");}
//						if(slots.optJSONObject("location") != null)
//						{location = slots.optJSONObject("location");}
//					}
//					else if(operation.equals("VIEW"))
//					{
//						if(slots.optString("repeat") != null)
//						{repeat = slots.optString("repeat");}
//					}
					//语音合成进行回答
					//text = "智能提醒还在完善中，稍后就可以问我了";
					text = "智能提醒已设置好";
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("stock"))     //4.14----股票查询
				{
					ServiceType = "Stock";
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots    = semantic.optJSONObject("slots");
					String name,stock_code,category,chartType;
					JSONObject location;
					stock_code = "";
					category = "";
					if(slots.optString("name") != null)
					{name = slots.optString("name");}
					if(slots.optString("code") != null)
					{stock_code = slots.optString("code");}
					if(slots.optString("category") != null)
					{category = slots.optString("category");}
					if(slots.optString("chartType") != null)
					{chartType = slots.optString("chartType");}
					if(slots.optJSONObject("location") != null)
					{location = slots.optJSONObject("location");}
					
					if(category.length()>=1 && stock_code.length()>=1)  
					{
						JSON_url = "http://hq.sinajs.cn/list=" + category + stock_code;
						
						httpClientThread = new Thread(httpClientRunnable);
						httpClientThread.start();
						
						String gif_url = "http://image.sinajs.cn/newchart/daily/n/";
						gif_url = gif_url + category + stock_code + ".gif";
						RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, gif_url);
						text = "股票查询还在完善中，稍后就可以问我了";
					}
					else
					{
						//语音合成进行回答
						text = "股票查询还在完善中，稍后就可以问我了";
						code = mTts.startSpeaking(text, mTtsListener2);
						if (code != ErrorCode.SUCCESS) {
							Log.d(TAG, "语音合成失败,错误码: " + code);}
					}
					
				}
				else if(service.equals("train"))     //4.15----火车查询
				{
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots    = semantic.optJSONObject("slots");
					
					JSONObject startLoc = slots.optJSONObject("startLoc");
					JSONObject endLoc   = slots.optJSONObject("endLoc");
					
					String date;
					if(slots.optJSONObject("startDate")!=null)
					{
						date = slots.optJSONObject("startDate").optString("date");
					}
					else
					{
						date = "";
					}
					String start_cityAddr = startLoc.optString("cityAddr");
					String end_cityAddr = endLoc.optString("cityAddr");
					
					String url = "http://touch.train.qunar.com/trainList.html?";
					if(start_cityAddr.length()>=1)
					{
						url = url + "startStation=" + start_cityAddr + "&";
						url = url + "endStation=" + end_cityAddr + "&";
						url = url + "date=" + date + "&";
						url = url + "searchType=stasta";
						RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
					}
					else
					{
						if(Location_City.length()>=1)
						{
							url = url + "startStation=" + Location_City.substring(0,Location_City.length()-1) + "&";
							url = url + "endStation=" + end_cityAddr + "&";
							url = url + "date=" + date + "&";
							url = url + "searchType=stasta";
							RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
							text = "已查找到"+date+Location_City.substring(0,Location_City.length()-1)+"到"+end_cityAddr+"的火车";
						}
						else
						{
							text = "定位失败，你可以对我说帮我查找明天从无锡到上海的火车";
						}
					}
					
					//语音合成进行回答
					
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("translation"))  //4.16----翻译
				{
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots    = semantic.optJSONObject("slots");
					String content,source,target;
					content = slots.optString("content");
					source  = slots.optString("source");
					target  = slots.optString("target");
					
					//语音合成进行回答
					text = "翻译还在完善中，稍后就可以问我了";
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("tv"))        //4.17-----电视节目
				{
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots    = semantic.optJSONObject("slots");
					
					JSONObject startTime;
					String tvName,programType,programName;
					if(slots.optJSONObject("startTime") != null)
					{startTime = slots.optJSONObject("startTime");}
					if(slots.optString("tvName") != null)
					{tvName = slots.optString("tvName");}
					if(slots.optString("programType") != null)
					{programType = slots.optString("programType");}
					if(slots.optString("programName") != null)
					{programName = slots.optString("programName");}
					
					
//					Intent intent = new Intent();
//					intent.setClass(MainActivity.this, WebActivity.class);
//					intent.putExtra("url", url);
//					MainActivity.this.startActivity(intent);
					
					//语音合成进行回答
					text = "电视节目功能还在完善中，稍后就可以问我了";
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("video"))      //4.18-----视频
				{
					ServiceType = "Video";
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots;
				
					Intent intent = new Intent();
					intent.setAction("com.allthings.video");  
	                intent.putExtra("CMD", "Finish");
	                sendBroadcast(intent);
	                
	                if(semantic.optJSONObject("slots")!=null)
					{
						slots = semantic.optJSONObject("slots");
//						String keywords = "";
//						String actor = "";
//						String director = "";
//						String videoCategory = "";
//						String episode = "";
						if(slots.optString("keywords").length()>1)
						{
							video_keywords = slots.optString("keywords");
						}
						if(slots.optString("videoCategory").length()>1) //我想看XX类型的视频
						{
							video_videoCategory = slots.optString("videoCategory");
						}
						if(slots.optString("actor").length()>1)//我想看XX演员的电影
						{
							video_actor = slots.optString("actor");
						}
						if(slots.optString("director").length()>1)//我想看XX导演的电影
						{
							video_director = slots.optString("director");
						}
						if(slots.optString("episode").length()>1) //我想看XX电视剧第X集
						{
							video_episode = slots.optString("episode");
						}
						
						video_Thread = new Thread(videoRunnable);
						video_Thread.start();
						//Online_Video(video_keywords,video_videoCategory,video_actor,video_director,video_episode);
					}

//					String url = url = "http://www.youku.com/";
//					if(semantic.optJSONObject("slots")!=null)
//					{
//						slots    = semantic.optJSONObject("slots");
//						String keywords,actor,director;
//						String videoCategory;			
//						JSONObject datetime;
//						String tvchannel,popularity;
//						
//						if(slots.optString("keywords").length()>1)
//						{
//							keywords = slots.optString("keywords");
//							url = "http://www.soku.com/m/y/video?q="+keywords;
//						}
//						else if(slots.optString("actor").length()>1)
//						{
//							actor = slots.optString("actor");
//							url = "http://www.soku.com/m/y/video?q="+actor;
//						}
//						else if(slots.optString("director").length()>1)
//						{
//							director = slots.optString("director");
//							url = "http://www.soku.com/m/y/video?q="+director;
//						}
//						else if(slots.optString("videoCategory").length()>1)
//						{
//							videoCategory = slots.optString("videoCategory");
//							if(videoCategory.contains("综艺"))
//								{url = "http://www.soku.com/m/y/video?q="+videoCategory+"节目";}
//							else if(videoCategory.contains("电视剧"))
//								{url = "http://www.soku.com/m/y/video?q="+videoCategory;}
//							else 
//								{url = "http://www.soku.com/m/y/video?q="+videoCategory+"电影";}
//						}
//					}
//					else
//					{
//						url = "http://www.youku.com/";
//					}
//					//直接进行网页跳转
//				RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
//				语音合成进行回答
					text = "已经为您搜索到相关的视频";
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				
				
				
				else if(service.equals("weather"))   //4.19----天气查询
				{
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots   = semantic.optJSONObject("slots");
					
					JSONObject datetime = slots.optJSONObject("datetime");
					String userdate     = datetime.optString("date");
					
					JSONObject data     = object.optJSONObject("data");
					JSONArray result    = data.optJSONArray("result");
					
					JSONObject info = new JSONObject();
					for(int i = 0;i <= 6; i++) {
						info = result.optJSONObject(i);
						String date = info.optString("date");
						if(userdate.equals(date))
							break;
					}
					 
					String airQuality = "";
					if(info.optString("airQuality").equals("未知"))
					{airQuality = "暂无数据";}
					else
					{airQuality = info.optString("airQuality");}
					
					String humidity  = "";
					if(info.optString("airQuality") != null)
					{humidity = info.optString("humidity");}
					
					if(humidity.equals(""))
					{humidity = "暂无数据";}
					
					String date      = info.optString("date");
					String city      = info.optString("city");
					String weather   = info.optString("weather");
					String wind      = info.optString("wind");
					String tempRange = info.optString("tempRange");
					String windLevel = info.optString("windLevel");
					
					text = city + date;  //城市 + 日期 + 天气 +风力 + 温度 + 空气质量 + 湿度
					StringBuilder answer_1 = new StringBuilder("");
					answer_1  = answer_1.append(text);
					answer_1  = answer_1.append(",");
					answer_1  = answer_1.append(weather);
					answer_1  = answer_1.append(",");
					answer_1  = answer_1.append(wind);
					answer_1  = answer_1.append(",风力");
					answer_1  = answer_1.append(windLevel);
					answer_1  = answer_1.append("级，室内温度");
					answer_1  = answer_1.append(tempRange);
					answer_1  = answer_1.append("，空气质量");
					answer_1  = answer_1.append(airQuality);
					answer_1  = answer_1.append("，空气湿度");
					answer_1  = answer_1.append(humidity);
					
					String [] tempPoint = null; 
					tempPoint = tempRange.split("~");
					tempPoint[0] = tempPoint[0].substring(0, 2);
					tempPoint[1] = tempPoint[1].substring(0, 2);
					
					if(info.optString("airQuality").equals("未知"))
					{
						text = answer_1.toString();      //没有湿度和风力的情况下 不进行相关的播报
					}
					else
					{
						humidity = humidity.substring(0, 2);

						int T1 = Integer.parseInt(tempPoint[0]);
						int T2 = Integer.parseInt(tempPoint[1]);
						int t  = (T1+T2)/2;
						Log.d(TAG,"平均温度"+t);
						double f = Double.parseDouble(humidity);
						f=f/100;
						Log.d(TAG,"湿度"+f);
						int v_wind = Integer.parseInt(windLevel);
					
						double v =0;
						switch(v_wind)
						{
							case 0 :{v = 0.1; break;}
							case 1 :{v = 0.9; break;}
							case 2 :{v = 2.45; break;}
							case 3 :{v = 4.4; break;}
							case 4 :{v = 6.7; break;}
							case 5 :{v = 9.35; break;}
							case 6 :{v = 12.3; break;}
							case 7 :{v = 15.5; break;}
							case 8 :{v = 18.95; break;}
							case 9 :{v = 22.6; break;}
							case 10:{v = 26.45; break;}
							case 11:{v = 30.55; break;}
							case 12:{v = 34.8; break;}
							case 13:{v = 39.2; break;}
							case 14:{v = 43.8; break;}
							case 15:{v = 48.55; break;}
							case 16:{v = 53.5; break;}
							case 17:{v = 58.65; break;}
						}
						Log.d(TAG,"平均风速"+v+"米每秒");
						int ssd=(int)(((1.818*t+18.18)*(0.88+0.002*f))+((t-32)/(45-t))-(3.2*v)+18.2);
						Log.d(TAG,"人体舒适度指数"+ssd);
						
						answer_1  = answer_1.append(",人体舒适度指数"); 
						answer_1  = answer_1.append(ssd);
						
						if(ssd>=89)
						{answer_1  = answer_1.append(",从来都没有这么热过，多多要罢工了！");}
						else if(ssd>=86 && ssd<=88)       //体感舒适度指数 4级
						{answer_1  = answer_1.append(",天气炎热，不适合外出，一定注意防暑降温，以防中暑啊！");}
						else if(ssd>=80 && ssd<=85)  //体感舒适度指数 2级
						{answer_1  = answer_1.append(",天气炎热，尽量待在室内，注意防暑降温呀！");}
						else if(ssd>=76 && ssd<=79)  //体感舒适度指数 3级
						{answer_1  = answer_1.append(",感觉有点热，可以适当的进行降温哦！");}
						else if(ssd>=71 && ssd<=75)  //体感舒适度指数 1级
						{answer_1  = answer_1.append(",感觉有点暖和，出去转转走走吧！");}
						else if(ssd>=59 && ssd<=70)  //体感舒适度指数 0级
						{answer_1  = answer_1.append(",天气很好， 没有比这更适合外出的天气了呀！");}
						else if(ssd>=51 && ssd<=58)  //体感舒适度指数 -1级
						{answer_1  = answer_1.append(",可能感觉有点凉， 不过还好，外出记得带件衣服哦！");}
						else if(ssd>=39 && ssd<=50)  //体感舒适度指数 -2级
						{answer_1  = answer_1.append(",天气开始转凉啦， 注意保暖哟，如果还没有添衣服可以添件外套啦！");}
						else if(ssd>=26 && ssd<=38)  //体感舒适度指数 -3级
						{answer_1  = answer_1.append(",啊呀呀，天气好冷呀，多多都在发抖了，可要做好防寒保暖工作啊！");}
						else if(ssd<=25)  //体感舒适度指数 -4级
						{answer_1  = answer_1.append(",外面好冷，不适合外出，在家要防寒保暖，防止冻伤呢！");}
						
						text = answer_1.toString(); 
					}
					
					if(city.equals("台中"))
					{text ="您还没有告诉我要查询的是哪个城市的天气";}
					else
					{
						String package_name = "com.moji.mjweather";
						Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(package_name); 
						if(LaunchIntent != null){ startActivity(LaunchIntent); }
					}
					
					//if(ssd)
					//语音合成进行回答
					//text = "天气查询还在完善中，稍后就可以问我了";
					//text = answer_1.toString();
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("websearch"))  //4.20----网页搜索
				{
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots    = semantic.optJSONObject("slots");
					
					String channel,keywords;
					String url = "www.baidu.com";
					keywords = slots.optString("keywords");
					try {
						// address = URLEncoder.encode(address, "gb2312"); /////////百度搜索位置。
						url = "http://www.baidu.com.cn/s?wd="
								+ URLEncoder.encode(keywords, "gb2312");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(slots.optString("channel") != null)
					{
						channel = slots.optString("channel");
						RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
					}
					else
					{
						RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
					}
					//语音合成进行回答
					text = "已经为您搜索到" + keywords;
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("website"))    //4.21----登录网页
				{
					JSONObject semantic = object.optJSONObject("semantic");
					JSONObject slots    = semantic.optJSONObject("slots");
					
					String name;
					String url = "www.baidu.com";
					name = slots.optString("name");
					if(slots.optString("url") != null)
					{
						url = slots.optString("url");
						//有网址的时候，直接进行跳转
						RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
					}
					else
					{
						//当没有网址的时候 默认使用 百度 搜索 name对应的相关词条
						try {
							// address = URLEncoder.encode(address, "gb2312"); /////////百度搜索位置。
							url = "http://www.baidu.com.cn/s?wd="
									+ URLEncoder.encode(name, "gb2312");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						RomControl.enterControl(this, RomControl.ROM_BROWSER_URL, url);
					}
					
					//语音合成进行回答
					text = "已经为您打开" + name;
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("judgement"))   //4.26----褒贬功能
				{
					text = "褒贬功能还在完善中，稍后就可以问我了";
					//语音合成进行回答
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("greeting"))    //4.27-----问候
				{
					text = "问候功能还在完善中，稍后就可以问我了";
					//语音合成进行回答
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("mood"))       //4.28-----情绪
				{
					text = "情绪功能还在完善中，稍后就可以问我了";
					//语音合成进行回答
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("telephone"))   //4.29-----电话
				{
					Call_Phone();
				}
				else if(service.equals("message"))     //4.30----短信
				{
					text = "短信功能还在完善中，稍后就可以问我了";
					//语音合成进行回答
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("pm25"))        //4.31----空气质量
				{
					text = "空气质量功能还在完善中，稍后就可以问我了";
					//语音合成进行回答
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("chat"))        //4.32----闲聊
				{
					JSONObject answer = object.optJSONObject("answer");
					
					//语音合成进行回答
					text = answer.optString("text");
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else if(service.equals("openQA"))
				{
					JSONObject answer = object.optJSONObject("answer");
					
					//语音合成进行回答
					//text = "我知道的，但是那个傻逼程序员不让我告诉你";
					text = answer.optString("text");
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
				else
				{
					text = "我还不会那么多，您再慢慢讲一遍试试";
					//语音合成进行回答
					code = mTts.startSpeaking(text, mTtsListener2);
					if (code != ErrorCode.SUCCESS) {
						Log.d(TAG, "语音合成失败,错误码: " + code);}
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public void Xunfei_Stop()
	{
		/***销毁语音唤醒***/
		mIvw = VoiceWakeuper.getWakeuper();
		if (mIvw != null) {
			mIvw.destroy();
		} else {
			Log.d(TAG, "唤醒未初始化");
		}
		
		/***销毁语音合成***/
		mTts.stopSpeaking();
		// 退出时释放连接
		mTts.destroy();
		
		/***销毁语音听写***/
		// 退出时释放连接
		mIat.cancel();
		mIat.destroy();
		
		/***销毁语义理解***/
		// 退出时释放连接
    	mSpeechUnderstander.cancel();
    	mSpeechUnderstander.destroy();
    	
	}
	
	public void offline_Xunfei_Stop()
	{

		
		/***销毁语音合成***/
		mTts.stopSpeaking();
		// 退出时释放连接
		mTts.destroy();
		
		/***销毁语音听写***/
		// 退出时释放连接
		mIat.cancel();
		mIat.destroy();
		
    	
	}
	
	
	//网络连接状态判断
	private boolean checkNetworkState() {  
        boolean flag = false;  
        //得到网络连接信息  
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);  
        //去进行判断网络是否连接  
        if (manager.getActiveNetworkInfo() != null) {  
                flag = manager.getActiveNetworkInfo().isAvailable();  
        }  
         
        return flag;  
}
	
	

	
//高德定位函数
	public void startAmap() {
		//Location_City = "";
		//Location_District = "";
		aMapManager = LocationManagerProxy.getInstance(this);
		/*
		 * mAMapLocManager.setGpsEnable(false);
		 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true Location
		 * API定位采用GPS和网络混合定位方式
		 * ，第一个参数是定位provider，第二个参数时间最短是2000毫秒，第三个参数距离间隔单位是米，第四个参数是定位监听者
		 */
		aMapManager.requestLocationUpdates(LocationProviderProxy.AMapNetwork, 2000, 10, mAMapLocationListener);
	}
	
	public void stopAmap() {
		if (aMapManager != null) {
			aMapManager.removeUpdates(mAMapLocationListener);
			aMapManager.destory();
		}
		aMapManager = null;
	}
	
//定位回调函数，当未知发生变化时位置更新（常驻）
	String Location_Desc;
	
	public AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
			
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				
			}
			
			@Override
			public void onProviderEnabled(String provider) {
				
			}
			
			@Override
			public void onProviderDisabled(String provider) {
				
			}
			
			@Override
			public void onLocationChanged(Location location) {
				
			}
			
			@Override
			public void onLocationChanged(AMapLocation location) {
				if (location != null) {
					Double geoLat = location.getLatitude();
					Double geoLng = location.getLongitude();
					String cityCode = "";
					String desc = "";
					Bundle locBundle = location.getExtras();
					if (locBundle != null) {
						cityCode = locBundle.getString("citycode");
						desc = locBundle.getString("desc");
					}

					if(location.getCity().length()>1)
					{
						Location_City = location.getCity();
						Location_District = location.getDistrict();
						Location_Desc = locBundle.getString("desc");
						Location_CityCode = location.getAdCode();
						Location_Lng = geoLng;
						Location_Lat = geoLat;
					}
					
					
					String str = ("定位成功:(" + geoLng + "," + geoLat + ")"
							+ "\n精    度    :" + location.getAccuracy() + "米"
							+ "\n定位方式:" + location.getProvider() + "\n定位时间:"
							+ new Date(location.getTime()).toLocaleString() + "\n城市编码:"
							+ cityCode + "\n位置描述:" + desc + "\n省:"
							+ location.getProvince() + "\n市:" + location.getCity()
							+ "\n区(县):" + location.getDistrict() + "\n区域编码:" + location
							.getAdCode());
					
					Log.d("Gaode",str);
				}
			}
		};
		
		private String episode_flag = "No";
		
//http申请JSON返回，链接函数和解析函数	
		private Thread httpClientThread;	
		String JSON_url;
	
		Runnable httpClientRunnable = new Runnable() {
			
			@Override
			public void run() {
				
				DefaultHttpClient httpClinet = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(JSON_url);
				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				try {
					if(ServiceType.equals("Stock"))
					{
						String var_hq_str = httpClinet.execute(httpGet, responseHandler);
						Log.d("var_hq_str",var_hq_str);//查看具体返回参数
						String stock_data = var_hq_str.substring((var_hq_str.indexOf("=")+2), (var_hq_str.length()-3));
						String[] stock_detial;
						stock_detial = stock_data.split(",");
						String text = stock_detial[0];
						if(text.contains("指数"))
						{
							text = text + "，昨天收盘" + stock_detial[2] + "点";
							text = text + "，今日开盘" + stock_detial[1] + "点";
							text = text + "，当前" + stock_detial[3] + "点";
						}
						else
						{
							text = text + "，昨天收盘价" + stock_detial[2] + "元";
							text = text + "，今日开盘价" + stock_detial[1] + "元";
							text = text + "，当前价格" + stock_detial[3] + "元";
						}
					
						int code = mTts.startSpeaking(text, mTtsListener2);
						if (code != ErrorCode.SUCCESS) {
							Log.d(TAG, "语音合成失败,错误码: " + code);}
						Log.d("JSON","股票数据："+stock_data);
					}
					else if(ServiceType.equals("Music"))
					{
						try
						{
							String var_hq_str1 = httpClinet.execute(httpGet, responseHandler);
							Log.d("JSON",var_hq_str1);
							//JSONObject var_hq_str = new JSONObject(httpClinet.execute(httpGet, responseHandler));
							JSONObject var_hq_str = new JSONObject(var_hq_str1);
							Log.d("JSON","音乐数据："+var_hq_str);
							JSONArray song_list =  var_hq_str.optJSONArray("song_list");
							if(song_list!=null)
							{
								int list_size = song_list.length();

								String[] artistname = new String[list_size];
								String[] songname = new String[list_size];
								String[] songid = new String[list_size];
								for(int i=0; i<list_size; i++)
								{
									artistname[i] = song_list.getJSONObject(i).optString("author").toString();
									artistname[i] = artistname[i].replace("<em>","");
									artistname[i] = artistname[i].replace("</em>","");
									songname[i] = song_list.getJSONObject(i).optString("title").toString();
									songname[i] = songname[i].replace("<em>","");
									songname[i] = songname[i].replace("</em>","");
									songid[i] = song_list.getJSONObject(i).optString("song_id");
								}
								Online_Music(artistname,songname,songid);
								String text = "已取得音乐数据";
								int code = mTts.startSpeaking(text, mTtsListener2);
								if (code != ErrorCode.SUCCESS) {
									Log.d(TAG, "语音合成失败,错误码: " + code);}
							}
							else
							{
								String text = "网络连接失败";
								int code = mTts.startSpeaking(text, mTtsListener2);
								if (code != ErrorCode.SUCCESS) {
									Log.d(TAG, "语音合成失败,错误码: " + code);}
							}
						}
						catch(JSONException e)
						{}
						
					}
					else if(ServiceType.equals("Video"))//视频功能未完成
					{
						try
						{
							String youku_json = new String(httpClinet.execute(httpGet, responseHandler));
							Log.d("JSON","视频数据："+youku_json);
													
							JSONObject total = new JSONObject(youku_json);
							Log.d("JSON","视频数据："+total);
							JSONArray videos =  total.getJSONArray("videos");
							int videos_size = videos.length();
							
							String[] id = new String[videos_size];
							String[] tag = new String[videos_size];
							String[] title = new String[videos_size];
							
							for(int i=0; i<videos_size; i++)
							{
								id[i]    = videos.getJSONObject(i).optString("id");
								tag[i]   = videos.getJSONObject(i).optString("tags");
								title[i] = videos.getJSONObject(i).optString("title");
							}
							
						}	catch(JSONException e){}
						
						if(episode_flag.equals("Yes"))
						{
							episode_flag = "No";
						}
						else
						{
							
						}
					}
					ServiceType = "Null";
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		
//音乐在线播放器调用		
		private void Online_Music(String[] artistname,String[] songname,String[] songid)
		{
			//Intent intent=getPackageManager().getLaunchIntentForPackage("com.example.music");       //定义一个意图  
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.setClassName("com.allthings.music", "com.allthings.music.MainActivity");
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.putExtra("Online_Music_artistname", artistname);
			intent.putExtra("Online_Music_songname", songname);
			intent.putExtra("Online_Music_songid", songid);
			//intent.setClass(WindowService.this, com.example.music.Music.class); //实现跳转功能，从MainActivity控件跳转到Music控件里
			WindowService.this.startActivity(intent);    //启动意图
		
		}

//打电话
		private void Call_Phone()
		{
			Intent intent = new Intent(Intent.ACTION_MAIN);
			Log.d("Call_Phone", "启动另外一个activity");
			//需要安装环信的apk，这是对应环信apk的包名，和要启动包中的activity的名字
			intent.setClassName("com.easemob.chatuidemo", "com.easemob.chatuidemo.activity.SplashActivity");
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			WindowService.this.startActivity(intent);
			Log.d("Call_Phone", "activity已开启");
		}
		
		private Thread video_Thread;	
		Runnable videoRunnable = new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Online_Video(video_keywords,video_videoCategory,video_actor,video_director,video_episode);
			}
			
		};
		private void Online_Video(String keywords,String videoCategory,String actor,String director,String episode)
		{
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.setClassName("com.example.playerdemo", "com.example.playerdemo.MainActivity");
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.putExtra("Online_Video_keywords", keywords);
			intent.putExtra("Online_Video_videoCategory", videoCategory);
			intent.putExtra("Online_Video_actor", actor);
			intent.putExtra("Online_Video_director", director);
			intent.putExtra("Online_Video_episode", episode);
			WindowService.this.startActivity(intent);    //启动意图
			Log.d("fuck","startActivity");
		}

		//语音提醒................By Si xiangjun
		private void onTimeSet(int flag,int d, int h, int m,String content) {
			if(isBackground("com.cn.daming.deskclock")){
				Intent intent_alarm = new Intent();
				intent_alarm.setAction("com.cn.daming.deskclock");
				intent_alarm.putExtra("CMD", "Refresh");
				intent_alarm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent_alarm.putExtra("flag", flag);
				intent_alarm.putExtra("day", d);
				intent_alarm.putExtra("hour",h);
				intent_alarm.putExtra("minute",m);
				intent_alarm.putExtra("content",content);
				sendBroadcast(intent_alarm);
			}
			else{
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setClassName("com.cn.daming.deskclock" , "com.cn.daming.deskclock.DeskClockMainActivity");
			intent.putExtra("flag", flag);
			intent.putExtra("day", d);
			intent.putExtra("hour",h);
			intent.putExtra("minute",m);
			intent.putExtra("content",content);
			WindowService.this.startActivity(intent);
			Log.d("serviceStart","serviceStart");
			}
		}
		
	
	
	
	private void sound_get()
	{
		((AudioManager) getSystemService(AUDIO_SERVICE)).requestAudioFocus(
				   null, AudioManager.STREAM_MUSIC,
				   AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);    //获得声音播放焦点
		//mUserPreference.putString(UserPreference.Sound_State, "Mute");
		Intent intent = new Intent();  
        intent.setAction("com.allthings.music");  
        intent.putExtra("CMD", "Mute");
        sendBroadcast(intent);
        
        Intent intent_video = new Intent();
        intent_video.setAction("com.example.playerdemo");
        intent_video.putExtra("CMD", "Mute");
        sendBroadcast(intent_video);
	}
	
	public void sound_release()
	{
		((AudioManager) getSystemService(AUDIO_SERVICE))
		   .abandonAudioFocus(null);       //释放声音播放焦点
		//mUserPreference.putString(UserPreference.Sound_State, "Resume");
		Intent intent = new Intent();  
        intent.setAction("com.allthings.music");  
        intent.putExtra("CMD", "Resume");
        sendBroadcast(intent);
        
        Intent intent_video = new Intent();
        intent_video.setAction("com.example.playerdemo");
        intent_video.putExtra("CMD", "Resume");
        sendBroadcast(intent_video);
	}
	

	public boolean isBackground(String AppName){
		ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
		for(RunningAppProcessInfo appProcess : appProcesses)
		{
			if(appProcess.importance != RunningAppProcessInfo.IMPORTANCE_BACKGROUND)
			{
				Log.d("Activity_Judge","处于后台" + appProcess.processName);
			}else{
				Log.d("Activity_Judge","处于前台" + appProcess.processName);
			}
			if(appProcess.processName.equals(AppName) && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
				return true;
			}
		}
		return false;
	}
	
	
	
	
	
	
	
	
		
		
		
		
		
		
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	
}